<template>
    <el-tabs v-model="activeName" class="tabs" stretch>
        <el-tab-pane label="目录树" name="tree">
            <WidgetTree />
        </el-tab-pane>
        <el-tab-pane label="组件配置" name="widget">
            <el-form :model="widgetConfig" style="padding: 10px;">
                <el-form-item label="ID" v-if="widgetId">
                    <el-input v-model="widgetId" @change="widgetIdChange"></el-input>
                </el-form-item>
                <div v-if="widgetConfig && widgetConfig.isSubForm">
                    <el-form-item label="子表单标识">
                        <el-select @change="subFormIdChange" v-model="fieldId" placeholder="选择子表单标识" style="width: 100%"
                            filterable allow-create>
                            <el-option v-for="item in subForm" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </div>
                <div v-else-if="widgetConfig && widgetConfig.isFormItem">
                    <el-form-item label="字段标识">
                        <el-select v-if="widgetConfig.subFormId" @change="subFormfieldChange" v-model="fieldId"
                            placeholder="选择字段标识" style="width: 100%" filterable allow-create>
                            <el-option v-for="item in subFormFields[widgetConfig.subFormId] || []" :key="item.value"
                                :label="item.label" :value="item.value" />
                        </el-select>
                        <el-select v-else @change="fieldChange" v-model="fieldId" placeholder="选择字段标识"
                            style="width: 100%" filterable allow-create>
                            <el-option v-for="item in fields" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </div>
                <div v-for="(field, i) in attributes" :key="i">
                    <el-form-item v-if="field == 'cssClass'" label="样式">
                        <CssClassSelector v-model="widgetConfig.attributes[field]" />
                    </el-form-item>
                    <el-form-item v-else-if="attributesConfigRef[field]" :label="attributesConfigRef[field].label">
                        <component v-if="attributesConfigRef[field].component"
                            :is="attributesConfigRef[field].component.name"
                            v-bind="attributesConfigRef[field].component.bind" v-model="widgetConfig.attributes[field]">
                            <component v-if="attributesConfigRef[field].component.children"
                                v-for="(children, j) in attributesConfigRef[field].component.children" :key="j"
                                :is="children.name" v-bind="children.bind">
                                {{ children.content || '' }}
                            </component>
                        </component>
                        <el-input v-else v-model="widgetConfig.attributes[field]" />
                    </el-form-item>
                </div>
                <div v-if="widgetConfig && widgetConfig.options && widgetConfig.type === 'treeSelect'">
                    <el-form-item label="选项配置">
                        <TreeOptionEditor v-model="widgetConfig.options" />
                    </el-form-item>
                </div>
                <div v-else-if="widgetConfig && widgetConfig.options">
                    <el-form-item label="选项配置">
                        <el-button link type="primary" @click.stop="widgetConfig.options.push({})">+ 新增</el-button>
                    </el-form-item>
                    <div style="margin-bottom: 5px; display: flex; flex-direction: row; gap: 10px; align-items: center;"
                        v-for="(option, index) in widgetConfig.options" :key="index">
                        <el-input placeholder="标签名" style="width: 115px;" v-model="option.label"></el-input>
                        <el-input-number style="width: 115px;" placeholder="值" v-model="option.value"></el-input-number>
                        <el-button size="small" @click.stop="removeOption(index)" type="danger" circle
                            :icon="Delete"></el-button>
                    </div>
                </div>
                <div v-if="widgetConfig && widgetConfig.dict">
                    <el-form-item label="使用字典" label-width="70px">
                        <el-switch v-model="widgetConfig.dict.useDict"></el-switch>
                    </el-form-item>
                    <el-form-item label-width="70px" label="字典接口" v-if="widgetConfig.dict.useDict">
                        <el-input v-model="widgetConfig.dict.url"></el-input>
                    </el-form-item>
                    <el-form-item label-width="70px" label="显示字段" v-if="widgetConfig.dict.useDict">
                        <el-input v-model="widgetConfig.dict.labelKey"></el-input>
                    </el-form-item>
                    <el-form-item label-width="70px" label="值字段" v-if="widgetConfig.dict.useDict">
                        <el-input v-model="widgetConfig.dict.valueKey"></el-input>
                    </el-form-item>
                </div>
                <div v-if="widgetConfig && widgetConfig.isFormItem">
                    <ValidationEditor :config="widgetConfig" />
                </div>
                <div v-if="widgetConfig && eventNameList.length != 0">
                    <el-form-item v-for="name in eventNameList" :key="name" :label="name">
                        <EventEditor :config="widgetConfig" :eventName="name" />
                    </el-form-item>
                </div>
            </el-form>
        </el-tab-pane>
        <el-tab-pane label="表单配置" name="form">
            <el-form style="padding: 10px;" :model="formAttributesConfig">
                <div v-for="(field, i) in formAttributes" :key="i">
                    <el-form-item v-if="formAttributesConfig[field] && formAttributesConfig[field].component"
                        :label="formAttributesConfig[field].label">
                        <component :is="formAttributesConfig[field].component.name"
                            v-bind="formAttributesConfig[field].component.bind" v-model="formConfig[field]">
                            <component v-if="formAttributesConfig[field].component.children"
                                v-for="(children, j) in formAttributesConfig[field].component.children" :key="j"
                                :is="children.name" v-bind="children.bind">
                                {{ children.content || '' }}
                            </component>
                        </component>
                    </el-form-item>
                </div>
                <el-form-item label="onMounted">
                    <EventEditor :config="formConfig" eventName="onMounted" />
                </el-form-item>
                <el-form-item label="全局样式">
                    <GlobalStyleEditor v-model="formConfig.globalStyle"/>
                </el-form-item>
            </el-form>
        </el-tab-pane>
    </el-tabs>
</template>
<script setup>
import { inject, ref, watch, onMounted } from 'vue'
import { attributesConfig } from '@/utils/attributesConfig'
import { formAttributesConfig } from '@/utils/formConfig'
import ValidationEditor from './ValidationEditor.vue'
import EventEditor from './EventEditor.vue'
import GlobalStyleEditor from './GlobalStyleEditor.vue'
import CssClassSelector from './CssClassSelector.vue'
import TreeOptionEditor from './TreeOptionEditor.vue'
import WidgetTree from './WidgetTree.vue'
import { Delete } from '@element-plus/icons-vue'

import { ElMessage } from 'element-plus';
// 注入 designer
const designer = inject('designer')
const selectWidgetId = inject('selectWidgetId')
const widgetList = inject('widgetList')
const formConfig = inject('formConfig')
const fieldData = inject('fieldData')
const activeName = ref('form')

const attributesConfigRef = ref(attributesConfig)

const widgetConfig = ref(null)
const attributes = ref([])//组件属性列表
const formAttributes = ref([])//表单属性列表
const eventNameList = ref([])//组件事件列表

const getWidgetConfigData = () => {
    if (widgetList.value) {
        activeName.value = 'widget'
        widgetConfig.value = designer.getWidgetById(widgetList.value, selectWidgetId.value);
        // 加载组件属性
        widgetId.value = widgetConfig.value?.id
        if (widgetConfig.value && widgetConfig.value.attributes) {
            attributes.value = Object.keys(widgetConfig.value.attributes)
            if (widgetConfig.value.isCustomWidget && widgetConfig.value.attributesConfig) {//加载自定义组件属性配置
                attributesConfigRef.value = { ...attributesConfig, ...widgetConfig.value.attributesConfig }
            }
        } else {
            attributes.value = []
        }
        // 加载组件事件
        if (widgetConfig.value && widgetConfig.value.events) {
            eventNameList.value = Object.keys(widgetConfig.value.events)
        } else {
            eventNameList.value = []
        }
        // 加载表单字段内容
        if (widgetConfig.value && (widgetConfig.value.isFormItem || widgetConfig.value.isSubForm)) {
            fieldId.value = widgetConfig.value.fieldId || ''
            syncFieldsData()
        }
    }
}

const removeOption = (index) => {
    widgetConfig.value.options.splice(index, 1);
};

// 组件的全局标识
const widgetId = ref(null)
const widgetIdChange = (value) => {
    const isUnique = designer.isUniqueId(value, widgetList.value)
    if (isUnique) {
        selectWidgetId.value = value
        widgetConfig.value.id = widgetId.value
    } else {
        widgetId.value = widgetConfig.value.id
        ElMessage.info('组件唯一标识重复！')
    }
}

// 抽离出字段标识和子表标识
const fields = ref([])
const subForm = ref([])
const subFormFields = ref({})

const syncFieldsData = () => {
    fields.value = fieldData.value?.fields || []
    subForm.value = fieldData.value?.children || []

    subFormFields.value = subForm.value.reduce((acc, item) => {
        if (item.value && Array.isArray(item.fields)) {
            // 在 widgetList 中查找匹配的组件
            const match = designer.getSubFormWidgetByFieldId(widgetList.value, item.value)
            if (match && match.id) {
                acc[match.id] = item.fields
            }
        }
        return acc
    }, {})
}
// 控制主表字段标识的选择
const fieldId = ref('')
const fieldChange = (value) => {
    const isUnique = designer.isFormFieldIdUnique(value, widgetList.value)
    if (isUnique) {
        widgetConfig.value['fieldId'] = value
        const item = fields.value.find(f => f.value === value)
        const label = item ? item.label : null
        if (label) {
            widgetConfig.value.attributes.label = label
        }
    } else {
        fieldId.value = widgetConfig.value.fieldId
        ElMessage.info('字段标识重复！')
    }
}
// 控制子表标识的选择
const subFormIdChange = (value) => {
    const isUnique = designer.isFormFieldIdUnique(value, widgetList.value)
    if (isUnique) {
        widgetConfig.value['fieldId'] = value
        const item = subForm.value.find(f => f.value === value)
        const label = item ? item.label : null
        if (label) {
            widgetConfig.value.attributes.label = label
        }
    } else {
        fieldId.value = widgetConfig.value.fieldId
        ElMessage.info('子表单标识重复！')
    }
}
// 控制子表字段标识的选择
const subFormfieldChange = (value) => {
    const isUnique = designer.isFormFieldIdUnique(value, widgetList.value, widgetConfig.value.subFormId)// 控制查询域只在对应子表
    if (isUnique) {
        widgetConfig.value['fieldId'] = value
        const item = subFormFields.value[widgetConfig.value.subFormId]?.find(f => f.value === value)
        const label = item ? item.label : null
        if (label) {
            widgetConfig.value.attributes.label = label
        }
    } else {
        fieldId.value = widgetConfig.value.fieldId
        ElMessage.info('子表单字段标识重复！')
    }
}

watch(selectWidgetId, (newVal, oldVal) => {
    if (newVal) {
        getWidgetConfigData()
    } else {
        widgetId.value = null
        attributes.value = []
        widgetConfig.value = null
    }
})

onMounted(() => {
// 初始化表单配置信息
    formAttributes.value = Object.keys(formConfig.value)
})
</script>
<style scoped>
.tabs {
    margin: 0px;
    padding-bottom: 20px;
}

::v-deep(.el-form-item) {
    margin-bottom: 10px !important;
}

::v-deep(.el-tabs__header) {
    padding: 0 !important;
    margin: 0px !important;
}
</style>